
#pragma once

#include <stdint.h>
#include <assert.h>
#include "crypto-macros.h"


inline void _nettle_write_be32(size_t length, uint8_t *dst, const uint32_t *src)
{
    size_t i;
    size_t words;
    unsigned leftover;

    words = length / 4;
    leftover = length % 4;

    for (i = 0; i < words; i++, dst += 4)
        WRITE_UINT32(dst, src[i]);

    if (leftover)
    {
        uint32_t word;
        unsigned j = leftover;

        word = src[i];

        switch (leftover)
        {
        default:
            assert(0);
        case 3:
            dst[--j] = (word >> 8) & 0xff;
            /* Fall through */
        case 2:
            dst[--j] = (word >> 16) & 0xff;
            /* Fall through */
        case 1:
            dst[--j] = (word >> 24) & 0xff;
        }
    }
}

inline void _nettle_write_le32(size_t length, uint8_t *dst, const uint32_t *src)
{
    size_t i;
    size_t words;
    unsigned leftover;

    words = length / 4;
    leftover = length % 4;

    for (i = 0; i < words; i++, dst += 4)
        LE_WRITE_UINT32(dst, src[i]);

    if (leftover)
    {
        uint32_t word;

        word = src[i];

        do
        {
            *dst++ = word & 0xff;
            word >>= 8;
        } while (--leftover);
    }
}

inline void _nettle_write_le64(size_t length, uint8_t *dst, const uint64_t *src)
{
    size_t i;
    size_t words;
    unsigned leftover;

    words = length / 8;
    leftover = length % 8;

    for (i = 0; i < words; i++, dst += 8)
        LE_WRITE_UINT64(dst, src[i]);

    if (leftover)
    {
        uint64_t word;

        word = src[i];

        do
        {
            *dst++ = word & 0xff;
            word >>= 8;
        } while (--leftover);
    }
}